# -*- coding: utf-8 -*-
"""
Created on Tue Apr 21 14:47:14 2020

@author: Farman
"""

import numpy as np
import PIL.Image as img
import os
import joblib
import pathlib
import sys



def get_band_scenes_from_array(image_array, work_path):
    '''
    Generate single band scenes from array of multi-scene.

    Parameters
    ----------
    image_array : numpy array.
        Numpy array contains multi-scene.

    work_path : string.
        sub-path for single band scenes saving.
        
    Returns
    -------
    None.

    '''
    work_path = pathlib.Path(work_path)
    
    try:
        os.mkdir(work_path)
    except:
        pass
    
    band_num = image_array.shape[2]
    
    for n in range(band_num):
        band = image_array[:, :, n]
        band = np.array(band, dtype='uint32')
        band = band * 255 / band.max()
        band = np.array(band, dtype='uint8')
        pic = img.fromarray(band)
        #pic.show()
        name = work_path / ('band%03d.png'%n)
        print('Saving', name)
        pic.save(name)
    
    return



def get_band_scenes_from_persistence(persistence_file):
    '''
    Generate single band scenes from array persistence of multi-scene.

    Parameters
    ----------
    persistence_file : string.
        Persistence file of python3 numpy array of multi-scene.

    Returns
    -------
    None.

    '''
    file_name = pathlib.Path(persistence_file)
    data_scene = joblib.load(file_name)
    work_path = file_name.parent
    
    for k in data_scene.keys():
        print('Processing %s'%(work_path /k))
        get_band_scenes_from_array(data_scene.get(k), work_path / k)
        
    print('Job done.')
    return



if __name__ == '__main__':
    print('-' * 40, '\n')
    print('          Scene Image Generator\n')
    print('-' * 40, '\n')

    
    if len(sys.argv) == 1:        
        ans = input('Scenes python3 persistence file : ')
        
        if len(ans):
            get_band_scenes_from_persistence(ans)
        else:
            print('Usage:')
            print('python3 SceneImageGen.py')
            print('or')
            print('python3 SceneImageGen.py persistence_file_of_numpy_array.')
            
    elif len(sys.argv) == 2:
        get_band_scenes_from_persistence(sys.argv[1])
    else:
        print('Usage:')
        print('python3 SceneImageGen.py')
        print('or')
        print('python3 SceneImageGen.py persistence_file_of_numpy_array.')